package me.ingxin.android.permission2.view.impl

import android.app.Dialog
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import me.ingxin.android.permission2.R
import me.ingxin.android.permission2.getSupportSpecialPermissionName
import me.ingxin.android.permission2.view.GuideView
import me.ingxin.android.permission2.view.permissionMapOnQ
import me.ingxin.android.permission2.view.permissionMapOnR
import me.ingxin.android.permission2.view.permissionMapOnS
import me.ingxin.android.permission2.view.permissionMapOnT

/**
 * Created on 2023/8/5 by yin
 * 使用dialog实现引导对话框
 */
open class DefaultDialog(context: Context) : Dialog(context, R.style.PX_Permission_Dialog),
    GuideView {

    override var continueBlock: ((GuideView) -> Unit)? = null
    override var interruptBlock: ((GuideView) -> Unit)? = null

    override fun applyShow() {
        show()
    }

    override fun applyDismiss() {
        dismiss()
    }

    override fun disableCancelable() {
        setCancelable(false)
        setCanceledOnTouchOutside(false)
    }

    /**
     * 获取该权限所在的分组
     */
    protected fun getPermissionGroup(permission: String): String? {
        val osVersion = Build.VERSION.SDK_INT
        val group = when {
            osVersion < Build.VERSION_CODES.Q -> try {
                val permissionInfo = context.packageManager.getPermissionInfo(permission, 0)
                permissionInfo.group
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                null
            }

            osVersion == Build.VERSION_CODES.Q -> permissionMapOnQ[permission]
            osVersion == Build.VERSION_CODES.R -> permissionMapOnR[permission]
            osVersion == Build.VERSION_CODES.S -> permissionMapOnS[permission]
            osVersion == Build.VERSION_CODES.TIRAMISU -> permissionMapOnT[permission]
            else -> permissionMapOnT[permission]
        }
        Log.d("DefaultReasonDialog", "$permission -- $group")
        return group
    }

    /**
     * 获取特殊权限的名字
     */
    protected fun getSpecialPermissionName(permission: String): String =
        getSupportSpecialPermissionName(context, permission)

}